package cn.tansanqinger.xml;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

public class DOM4JDemo {
    public static void main(String[] args) throws Exception{
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("general/resources/person.xml"));
        // 获取根元素
        Element root = document.getRootElement();
        System.out.println("根: " + root.getName());
        // 获取所有子元素
        List<Element> childList = root.elements();//root.elements("persons");//获取名称为person的子元素
        System.out.println("一级子元素个数: " + childList.size());
        // 得到p1
        List<Element> list = root.elements("person");
        // 遍历list
        for (Element element : list) {
            List<Element> listElement = element.elements();
            for (Element element1 : listElement){
                if(element1.getName().equalsIgnoreCase("birthday")){
                    List<Element> list1 = element1.elements();
                    System.out.print("birthday:  ");
                    for(Element element2 : list1){
                        System.out.print(element2.getText()+"-");
                    }
                    System.out.println();
                } else {
                    System.out.println(element1.getName() + ": " + element1.getText());
                }
            }
        }
    }
}
